import errorCodesBuilder from '../../helpers/errorCodesBuilder';
import warningCounts from '../../helpers/warningCounts';

const errorCodes = errorCodesBuilder('取消忽略告警失败');

export default {
	description: '取消忽略告警',
	type: 'Task',
	args: {
		taskId: 'MongoID!',
		warnIds: '[String]!',
	},
	resolve: async (root, { taskId, warnIds }, { request }) => {
		const {
			server: {
				app: {
					model: { Task, Job },
				},
			},
			auth: {
				credentials: { uid, permissionMap },
			},
		} = request;

		let task;
		try {
			const query = { _id: taskId };
			if (!permissionMap[`cloud-monitor\x01editTask\x010`]) {
				query.uid = uid;
			}
			task = await Task.findOne(query);
		} catch (err) {
			const error = errorCodes['[01]取消忽略告警:查找任务mongo记录失败'].from(
				err
			);
			request.log.error({ error }, error.rawMessage);
			throw error;
		}

		if (!task) {
			const error = errorCodes['[01]取消忽略告警:没有找到对应mongo记录'];
			request.log.error({ taskId, warnIds }, error.internalMessage);
			throw error;
		}

		if (!task.isLatestTask) {
			const error = errorCodes['[01]取消忽略告警:不能修改非最后一次任务状态'];
			request.log.error({ error }, error.rawMessage);
			throw error;
		}

		const job = task.refId;
		const unignoreWarnTitle = [];
		const jobUpdateFields = {};
		const warnIdMap = warnIds.reduce((obj, x) => {
			obj[x] = true;
			return obj;
		}, {});
		task.result.warnings = task.result.warnings.map(x => {
			if (warnIdMap[x.id]) {
				unignoreWarnTitle.push(x.title);
				x.ignoredTime = null;
				jobUpdateFields[`ignoredWarnIdMap.${x.id}`] = null;
			}
			return x;
		});
		Object.assign(task.result, warningCounts(task.result.warnings));
		task.securityStatus = 'warning';

		try {
			task.refId = job._id;
			Promise.all([
				task.save(),
				Job.updateOne({ _id: task.jobId }, { $set: jobUpdateFields }),
			]);
		} catch (err) {
			const error = errorCodes['[01]取消忽略告警：更新mongo记录失败'].from(err);
			request.log.error({ error }, error.rawMessage);
			throw error;
		}

		request.log.audit(
			{
				affects: [task.target],
				module: 'task',
				actionType: 'update',
				actionMessage: '修改告警状态',
				detail: unignoreWarnTitle.join(' \n'),
			},
			`[${task.target}]取消忽略告警`
		);

		return task;
	},
};
